package com.woyou.ui.activity;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import retrofit.RetrofitError;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.woyou.bean.City;
import com.woyou.bean.CodeListResult;
import com.woyou.bean.Info;
import com.woyou.bean.ShopItem;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.ShopListReq;
import com.woyou.service.LocationLoopService;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.adapter.ShopListAdapter;
import com.woyou.ui.adapter.ShopSearchAdapter;
import com.woyou.ui.api.DefScrollListener;
import com.woyou.ui.api.DefScrollListener.DefScrollCallBack;
import com.woyou.ui.api.IBackEventStrategy;
import com.woyou.ui.api.IKeyEventStrategy;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.ErrorHintView.OperateListener;
import com.woyou.ui.component.fastscroll.FastScrollView;
import com.woyou.ui.component.fastscroll.IdleListDetector;
import com.woyou.ui.component.fastscroll.IdleListener;
import com.woyou.ui.fragment.ShopsFragment_;
import com.woyou.utils.CharCheckUtil;
import com.woyou.utils.Task;

/**
 * 搜索店铺
 * 
 * @author nsz 2015年1月22日
 */
@EActivity(R.layout.fm_shops_search)
public class ShopsSearchActivity extends BaseActivity implements IBackEventStrategy, IKeyEventStrategy {
	
	private List<String> keys = new ArrayList<String>();

	@ViewById(R.id.shop_search_edit)
	EditText searchEd; // 输入编辑框
	@ViewById(R.id.shop_search)
	TextView shopSearch; // 搜索按钮
	@ViewById(R.id.search_delete_all)
	TextView delete;
	@ViewById(R.id.left)
	RelativeLayout left;
	@ViewById(R.id.keys_bg)
	RelativeLayout keysbgRl;
	@ViewById(R.id.keysList)
	ListView keysList;

	@ViewById(R.id.shopsearch_history_rl)
	RelativeLayout historyRl; // 清除历史记录
	@ViewById(R.id.shopsearch_history_tv)
	TextView historyTv;

	@ViewById(R.id.shopsearch_clear)
	RelativeLayout clearRl; // 是否确定清除历史记录
	@ViewById(R.id.shopsearch_confirm)
	TextView confirm;
	@ViewById(R.id.shopsearch_cancel)
	TextView cancel;

	@ViewById(R.id.addrsearch_clear_item)
	RelativeLayout clearItemRl; // 清除单条记录
	@ViewById(R.id.shop_clear)
	TextView clearTv;
	@ViewById(R.id.confirm_item)
	TextView confirmItem;
	@ViewById(R.id.cancel_item)
	TextView cancelItem;

	@ViewById(R.id.hintView)
	ErrorHintView mErrorHintView;

	@ViewById(R.id.shopsearch_fastScrollView)
	FastScrollView fastScrollView;
	@ViewById(R.id.shopsearch_shopslist)
	ListView shopsListView;
	List<ShopItem> shopItems = new ArrayList<ShopItem>(); // listview数据源
	ShopListAdapter shopAdapter;
	ShopListReq shopListReq = new ShopListReq();

	private FastScrollView fastScroller; // 快速滚动器
	private IdleListener idleListener; // 空闲监听器
	private IdleListDetector mPostScrollLoader; // 空闲状态解析器

	ShopSearchAdapter shopSearchAdapter;
	KeysHistoryListener historyListener = new KeysHistoryListener();
	String searchKey; // 输入框搜索的关键字
	double lat, lng;
	UserInfo userInfo;

	/** 显示搜索关键字 **/
	private int VIEW_KEYS = 0;
	/** 显示店铺列表 **/
	private int VIEW_SHOPS = 1;
	/** 显示断网 **/
	private int VIEW_WIFIFAILUER = 2;
	/** 显示加载数据失败 **/
	private int VIEW_LOADFAILURE = 3;
	/** 显示加载中 **/
	private int VIEW_LOADING = 4;
	/** 显示请求超时 **/
	private int VIEW_OUTTIME = 5;
	/** 显示没有数据 **/
	private int VIEW_NOSHOPS = 6;

	@AfterViews
	public void init() {
		left.setOnClickListener(this);
		shopSearch.setOnClickListener(this);
		delete.setOnClickListener(this);
		confirm.setOnClickListener(this);
		cancel.setOnClickListener(this);
		historyTv.setOnClickListener(this);
		confirmItem.setOnClickListener(this);
		cancelItem.setOnClickListener(this);

		initData();
		initListView();
		initClickEvent();
		refreshKeys();
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		userInfo = mUserModel.getUserInfo();
		if (mBaiduLocationService.getLastLocation() != null) {
			lat = mBaiduLocationService.getLastLocation().getLatitude();
			lng = mBaiduLocationService.getLastLocation().getLongitude();
		}
	}

	private void initListView() {
		if (shopSearchAdapter == null) {
			shopSearchAdapter = new ShopSearchAdapter(keys, mContext);
			keysList.setAdapter(shopSearchAdapter);
		}
		clearTv.setText("删除选中关键字？");
		if (shopAdapter == null) {
			shopAdapter = new ShopListAdapter(shopItems, mContext);
			shopsListView.setAdapter(shopAdapter);
			setupIdleListener(shopsListView);
			// 监听ListView滚动
			fastScrollView.setScrollListener(new DefScrollListener(shopItems, mContext, new DefScrollCallBack() {
				@Override
				public void callBack() {
					showProgressDialog();
					refreshData(false);
				}
			}));
		}

		searchEd.addTextChangedListener(new TextWatcher() { // 初始化搜素记录
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				
			}

			@Override
			public void afterTextChanged(Editable s) {
				String key = s.toString();
				if (key.length() > 0) {
					delete.setVisibility(View.VISIBLE);
					shopSearch.setVisibility(View.VISIBLE);
					// onSearch(); // 输入信息的回调方法
				} else {
					delete.setVisibility(View.GONE);
					shopSearch.setVisibility(View.GONE);
					showViewById(VIEW_KEYS);
				}
			}
		});
	}

	protected void setupIdleListener(AbsListView list) {
		idleListener = new IdleListener(list, 0);
		mPostScrollLoader = new IdleListDetector(idleListener);
		fastScroller = (FastScrollView) list.getParent();
		fastScroller.setOnIdleListDetector(mPostScrollLoader);
	}


	@ItemClick(R.id.shopsearch_shopslist)
	void shopListItemClick(int position) {
		ShopItem shopItem = shopItems.get(position);
		// 跳转到店铺详情,在店铺里面拉取数据
		Info<ShopItem> info = new Info<ShopItem>(shopItem);
		info.setOrigin(ShopsSearchActivity_.class);
		openActivity(ShopInfoActivity.class, info);
	}

	/**
	 * 刷新关键字列表
	 */
	public void refreshKeys() {
		List<String> searchKeys = mShopsModel.getSearchKeys();
		for (String str : searchKeys) {
			if (!TextUtils.isEmpty(str) && !keys.contains(str)) {
				keys.add(str);
			}
		}
		if (keys != null && keys.size() > 0) {
			shopSearchAdapter.notifyDataSetChanged();
			historyRl.setVisibility(View.VISIBLE); // 出现清除按钮
		} else {
			historyRl.setVisibility(View.GONE);
		}
	}

	private String removeKeys; // 需要移除的关键字

	private void initClickEvent() {
		keysList.setOnItemClickListener(historyListener);

		keysList.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				if (clearRl.getVisibility() == View.GONE && clearItemRl.getVisibility() == View.GONE) {
					removeKeys = keys.get(position);
					clearItemRl.setVisibility(View.VISIBLE);
					hideSoftInput(mContext, searchEd);
					keysList.setOnItemClickListener(null);
					clearItemRl.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							clearItemRl.setVisibility(View.GONE);
							keysList.setOnItemClickListener(historyListener);
						}
					});
				}
				return false;
			}
		});
	}

	class KeysHistoryListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if (clearRl.getVisibility() == View.GONE && clearItemRl.getVisibility() == View.GONE) {
				showViewById(VIEW_LOADING);

				String myAddress = keys.get(position);
				searchEd.setText(myAddress);
				shopItems.clear();
				pageNext = 1;
				onSearch();
			}
		}

	}

	/**清空历史记录*/
	public void clearKeys() {
		keys.clear();
		mShopsModel.updateKeys(keys);
		refreshKeys();
	}

	/**搜索商家*/
	public void onSearch() {
		hideSoftInput(mContext, searchEd);
		searchKey = searchEd.getText().toString();
		refreshData(true);
	}

	private int pageNext = 1;
	
	private void refreshData(boolean clean) {
		lastTask = new RefreshDataTask(lastTask.getID() + 1, clean);
		executeTask(lastTask);
	}
	
	class RefreshDataTask extends Task {

		boolean flag = false; // 是否清空原数据

		public RefreshDataTask(int id, boolean flag) {
			super(id);
			this.flag = flag;
		}

		@Override
		public void run() {
			if (!NetWorkCenter.isNetworkConnected(mContext)) { 
				// 断网
				dismissProgressDialog();
				showViewById(VIEW_WIFIFAILUER);
				return;
			}
			if (pageNext == 0) {
				dismissProgressDialog();
				return;
			}
			
			shopListReq.setPage(pageNext); // 页号
			shopListReq.setScope("");
			shopListReq.setSortType("");
			if (LocationLoopService.getInstance(mContext).getChosenAddr() != null) {
				shopListReq.setLat(LocationLoopService.getInstance(mContext).getChosenAddr().getLat());
				shopListReq.setLng(LocationLoopService.getInstance(mContext).getChosenAddr().getLng());
			} else {
				shopListReq.setLat(lat + "");
				shopListReq.setLng(lng + "");
			}
			shopListReq.setCodeList(new String[] {}); // 店铺编号列表
			if (mBaiduLocationService.getLastLocation() != null) {
				String cityName = mBaiduLocationService.getLastLocation().getCity();
				shopListReq.setKey(searchKey);
				City city = new City();
				city.setCity(cityName);
				mUserModel.setCity(city);
			}

			if (userInfo == null) {
				userInfo = new UserInfo();
			}
			shopListReq.setuId(userInfo.getuId()); // 用户Id
			CodeListResult<ShopItem> result = null;
			try {
				result = mShopsModel.v2_3queryShopList(shopListReq);
			} catch (RetrofitError e) {
				switch (e.getKind()) {
				case HTTP:
					showViewById(VIEW_OUTTIME);
					return;
				case CONVERSION:
					showViewById(VIEW_LOADFAILURE);
					return;
				case NETWORK:
					showViewById(VIEW_OUTTIME);
					return;
				case UNEXPECTED:
					showViewById(VIEW_LOADFAILURE);
					return;
				}
			} finally {
				dismissProgressDialog();
			}

			// 判断是不是用户的最后操作,最后任务的ID如果比此任务的ID大则丢弃请求结果
			if (getID() < lastTask.getID()) {
				return;
			}
			
			if (result != null && result.code == 1) {
				refreshUI(result, flag);
				refreshKeysList();
			} else {
				showViewById(VIEW_LOADFAILURE);
			}

		}

	}

	/**更新关键字搜索列表*/
	@UiThread void refreshKeysList() {
		if (keys == null) {
			keys = new ArrayList<String>();
		}

		if (!keys.contains(searchKey)) {
			if (keys.size() == 10) {
				keys.remove(9);
			}

			keys.add(0, searchKey);
			mShopsModel.updateKeys(keys);
			refreshKeys();
		} else {
			keys.remove(searchKey);
			keys.add(0, searchKey);
			mShopsModel.updateKeys(keys);
			refreshKeys();
		}
	}

	@UiThread void refreshUI(CodeListResult<ShopItem> result, boolean flag) {
		List<ShopItem> list = result.getList();

		if (list == null || list.size() == 0) {
			showViewById(VIEW_NOSHOPS);
		} else {
			showViewById(VIEW_SHOPS);
			pageNext = result.page;
			shopItems.addAll(list);
			shopAdapter.notifyDataSetChanged();
			if (flag) {
				shopsListView.setSelection(0); // 列表置顶显示
			}
		}
	}

	private void defParams() {
		pageNext = 1;
		shopListReq.setKey("");
		searchEd.setText("");
		keysbgRl.setVisibility(View.VISIBLE);
		fastScrollView.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.left: // 返回键
			backOperate();
			break;

		case R.id.search_delete_all: // 删除键
			if (clearRl.getVisibility() == View.GONE && clearItemRl.getVisibility() == View.GONE) {
				searchEd.setText("");
				showViewById(VIEW_KEYS);
			}
			break;

		case R.id.shop_search: // 搜索键
			hideSoftInput(mContext, searchEd);
			searchKey = searchEd.getText().toString();
			if (clearRl.getVisibility() == View.GONE && clearItemRl.getVisibility() == View.GONE) {
				if (!TextUtils.isEmpty(searchKey) && !CharCheckUtil.isEmpty(searchKey)) {
					showViewById(VIEW_LOADING);

					shopItems.clear();
					pageNext = 1;
					onSearch();
				} else {
					showToast("湿主，洒家还不知道您要搜什么?");
				}
			}
			break;

		case R.id.shopsearch_confirm: // 确定全部记录
			clearKeys();
			clearRl.setVisibility(View.GONE);
			historyRl.setVisibility(View.GONE);
			keysList.setOnItemClickListener(historyListener);
			break;

		case R.id.shopsearch_cancel: // 取消
			clearRl.setVisibility(View.GONE);
			keysList.setOnItemClickListener(historyListener);
			break;

		case R.id.shopsearch_history_tv: // 清除历史记录
			hideSoftInput(mContext, searchEd);
			if (clearRl.getVisibility() == View.GONE && clearItemRl.getVisibility() == View.GONE) {
				clearRl.setVisibility(View.VISIBLE);
				keysList.setOnItemClickListener(null);
				clearRl.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						clearRl.setVisibility(View.GONE);
						keysList.setOnItemClickListener(historyListener);
					}
				});
			}
			break;

		case R.id.confirm_item: // 确定清除每一条记录
			if (removeKeys != null) {
				keys.remove(removeKeys);
				mShopsModel.updateKeys(keys);
				shopSearchAdapter.notifyDataSetChanged();
				if (keys.size() == 0) {
					historyRl.setVisibility(View.GONE);
				}
				clearItemRl.setVisibility(View.GONE);
				keysList.setOnItemClickListener(historyListener);
			}
			break;

		case R.id.cancel_item:
			clearItemRl.setVisibility(View.GONE);
			keysList.setOnItemClickListener(historyListener);
			break;

		default:
			break;
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.woyou.ui.activity.BaseActivity#onResume()
	 */
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		initData();
		initListView();
		keys.clear();
		refreshKeys();

	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean backOperate() {
		if (clearRl.getVisibility() == View.VISIBLE || clearItemRl.getVisibility() == View.VISIBLE) {
			clearRl.setVisibility(View.GONE);
			clearItemRl.setVisibility(View.GONE);
			return true;
			
		} else {
			hideSoftInput(mContext, searchEd);
			defParams();
			release();
			Info<Class> info = new Info<Class>(ShopsFragment_.class);
			info.setOrigin(ShopsSearchActivity_.class);
			openActivity(HomeActivity_.class, info);
			finish();
			return true;
		}
	}

	/**
	 * 返回退出时释放资源
	 */
	private void release() {
		if (shopAdapter != null) {
			shopAdapter.release();
			shopAdapter = null;
		}
		if (shopsListView != null) {
			shopsListView.setAdapter(null);
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// 拦截确定按钮事件
		if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
			searchKey = searchEd.getText().toString();
			if (!TextUtils.isEmpty(searchKey) && !CharCheckUtil.isEmpty(searchKey)) {
				showViewById(VIEW_LOADING);

				shopItems.clear();
				pageNext = 1;
				onSearch();
			} else {
				showToast("湿主，洒家还不知道您要搜什么?");
			}
			return true;
		}

		return super.dispatchKeyEvent(event);
	}

	/**显示搜索关键字:0 显示店铺列表：1 显示断网：2 显示加载数据失败：3 显示加载中：4 显示请求超时：5 显示没有数据：6*/
	@UiThread void showViewById(int i) {
		keysbgRl.setVisibility(View.GONE);
		fastScrollView.setVisibility(View.GONE);

		switch (i) {
		case 0:
			mErrorHintView.hideLoading();
			keysbgRl.setVisibility(View.VISIBLE);
			break;

		case 1:
			mErrorHintView.hideLoading();
			fastScrollView.setVisibility(View.VISIBLE);
			break;

		case 2:
			mErrorHintView.hideLoading();
			mErrorHintView.netError(new OperateListener() {
				@Override
				public void operate() {
					showViewById(VIEW_LOADING);
					refreshData(false);
				}
			});
			break;

		case 3:
			mErrorHintView.hideLoading();
			mErrorHintView.loadFailure(new OperateListener() {
				@Override
				public void operate() {
					showViewById(VIEW_LOADING);
					refreshData(false);
				}
			});
			break;

		case 4:
			mErrorHintView.loadingData();
			break;

		case 5:
			mErrorHintView.hideLoading();
			mErrorHintView.timeOut(new OperateListener() {
				@Override
				public void operate() {
					showViewById(VIEW_LOADING);
					refreshData(false);
				}
			});
			break;

		case 6:
			mErrorHintView.hideLoading();
			mErrorHintView.noShops("没找到关键字相关的店铺");
			break;
		}
	}

	@Override
	public boolean eventOperate(KeyEvent event) {
		return false;
	}
	

}
